/*

Copyright 2009 Nicola Dal Pont

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

package com.astoolkit.workflow.parsley
{
	import com.astoolkit.workflow.BasePipelineTask;
	import com.astoolkit.workflow.BaseTask;
	
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import mx.rpc.events.FaultEvent;
	
	import org.spicefactory.parsley.core.messaging.command.CommandObserverProcessor;
	import org.spicefactory.parsley.core.messaging.command.CommandStatus;
	import org.spicefactory.parsley.core.messaging.receiver.CommandObserver;
	import org.spicefactory.parsley.core.scope.Scope;
	import org.spicefactory.parsley.core.scope.ScopeName;
	
	[Bindable]
	public class SendParsleyMessage extends BasePipelineTask implements IParsleyCommandObserverTask
	{
		
		private var _processor : CommandObserverProcessor;
		
		private var _result : *;
		public var message : Object;
		public var selector : Object;
		
		/**
		 * if true this task will add a responder to the message's destination
		 * and will wait for a result or a fault event to be dispatched
		 * before completing.<br><br>
		 * 
		 * In Parsley terms, we use <code>isCommand="true"</code>
		 * to invoke a <code>[Command]</code> tagged function returning an AsyncToken.
		 * Otherwise, for a <code>[MessageHandler]</code> tagged function we set
		 *  <code>isCommand="false"</code>.
		 */
		public var isCommand : Boolean = false;
		
		private var _errorObserver : PrivateObserver;
		private var _completeObserver : PrivateObserver;
		private var _parsleyHelper : ParsleyMessageBusHelper;
		
		override public function initialize():void
		{
			if( !( context is IParsleyEnabledWorkflowContext || ( Object( context ).hasOwnProperty( "parsleyHelper" ) && context[ "parsleyHelper" ] is ParsleyMessageBusHelper ) ) ) 
			{
				fail( getQualifiedClassName( this ) + " cannot be ran because the provided " +
					"implementation of IWorkflowContext doesn't provide access to an instance of " +
					"ParsleyMessageBusHelper" );
				return;
			}
		}
		
		override public function prepare():void
		{
			super.prepare();
			_result = null;
		}
		
		public function get errorObserver() : CommandObserver 
		{
			return _errorObserver;
		}
		
		public function get completeObserver() : CommandObserver 
		{
			return _completeObserver;
		}
		
		override protected function complete():void
		{
			super.complete();
		}
		
		private function onObserverCommandComplete( inEvent : Event ) : void
		{
			if( isCommand )
			{
				removeSuspendableListener( _completeObserver, Event.COMPLETE, onObserverCommandComplete );
				removeSuspendableListener( _errorObserver, FaultEvent.FAULT, onObserverCommandFault );
			}
			_result = _completeObserver.result;
			_pipelineData = _result;
			complete();
		}
		
		private function onObserverCommandFault( inEvent : FaultEvent ) : void
		{
			if( isCommand )
			{
				removeSuspendableListener( _completeObserver, Event.COMPLETE, onObserverCommandComplete );
				removeSuspendableListener( _errorObserver, FaultEvent.FAULT, onObserverCommandFault );
			}
			fail( inEvent.message as String );
		}
		
		
		
		override public function cleanUp():void
		{
			super.cleanUp();
			_result = null;
			if( isCommand )
			{
				if( _parsleyHelper)
					_parsleyHelper.unwireAsyncCommandTask( this );
				_completeObserver = null;
				_errorObserver = null;
			}
		}

		override public function begin(inRetain:Boolean=false):void
		{
			super.begin( inRetain );
			_parsleyHelper = ParsleyMessageBusHelper( context[ "parsleyHelper" ] );
			
			if( isCommand )
			{
				var clazz : Class = getDefinitionByName( getQualifiedClassName( message ) ) as Class;
				_completeObserver = new PrivateObserver( clazz, CommandStatus.COMPLETE );
				_errorObserver = new PrivateObserver( clazz, CommandStatus.ERROR );
				_completeObserver.selector = selector;
				_errorObserver.selector = selector;
				_parsleyHelper.wireAsyncCommandTask( this, clazz );
				addSuspendableListener( _completeObserver, Event.COMPLETE, onObserverCommandComplete ); 
				addSuspendableListener( _errorObserver, FaultEvent.FAULT, onObserverCommandFault );
			}
			_parsleyHelper.context.scopeManager.getScope( ScopeName.GLOBAL ).dispatchMessage( message, selector );
			if( !isCommand )
				complete();
		}
			
		
		/**
		 * if <code>isCommand="true"</code>, <code>result</code> will contain 
		 * the data coming from the async operation.
		 */
		public function get result() : *
		{
			return _result;
		}
		
	}
}

import avmplus.getQualifiedClassName;

import com.astoolkit.workflow.parsley.SendParsleyMessage;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.getDefinitionByName;

import mx.rpc.AsyncToken;
import mx.rpc.Fault;
import mx.rpc.events.FaultEvent;

import org.spicefactory.parsley.core.messaging.command.CommandObserverProcessor;
import org.spicefactory.parsley.core.messaging.command.CommandStatus;
import org.spicefactory.parsley.core.messaging.receiver.CommandObserver;

class PrivateObserver extends EventDispatcher implements CommandObserver
{
	private var _selector : *;
	private var _processor : CommandObserverProcessor;
	private var _messageType : Class;
	private var _result : Object;
	private var _observedStatus : CommandStatus;
	
	public function PrivateObserver( inMessageType : Class, inStatus : CommandStatus )
	{
		_messageType = inMessageType;
		_observedStatus = inStatus;
	}
	
	public function get result() : Object
	{
		return _result;
	}
	
	public function get status () : CommandStatus
	{
		return _observedStatus;
	}
	
	// ------------- CommandObserver implementation -------------------//
	public function observeCommand ( inProcessor : CommandObserverProcessor ) : void
	{
		_processor = inProcessor;
		if( status.key == CommandStatus.COMPLETE.key )
		{
			_result = AsyncToken( inProcessor.command.returnValue ).result;
			
			dispatchEvent( new Event( Event.COMPLETE ) );
		}
		else if( status.key == CommandStatus.ERROR.key )
		{
			dispatchEvent( new FaultEvent( FaultEvent.FAULT, false, false, new Fault( "", _processor.command.returnValue as String ) ) );
		}
	}
	
	// ------------- MessageDispatcher implementation -------------------//
	public function get messageType() : Class
	{
		return _messageType;
	}
	
	public function get order() : int
	{
		return 1;
	}
	
	public function get selector() : *
	{
		return _selector;
	}
	
	public function set selector( inSelector : * ) : void
	{
		_selector = inSelector;
	}
	
	
}